import type { GreasyForkElements } from '../../../../../../../../../types/constants/personalization/greasy_fork'
import { ToolKit } from '../../../../../../../../../lib/utils/toolkit'
import {
  BodyClasses,
  PAGE_ELEMENTS,
  PROJECT_PREFIX,
  SUPPORTED_PLATFORMS,
} from '../../../../../../../../../types/constants'

// 测试链接：https://greasyfork.org/zh-CN/users/delete_info
export class DeleteInfoPage {
  elements: GreasyForkElements = PAGE_ELEMENTS[SUPPORTED_PLATFORMS.GREASY_FORK]
  private static instance: DeleteInfoPage
  private readonly selector: string = '.text-content'

  /**
   * 获取单例实例
   */
  public static getInstance(): DeleteInfoPage {
    if (!DeleteInfoPage.instance) {
      DeleteInfoPage.instance = new DeleteInfoPage()
    }
    return DeleteInfoPage.instance
  }

  init(): void {
    // 高亮邮箱
    this.highlightEmail()
  }

  /**
   * 高亮邮箱
   */
  private highlightEmail(): void {
    const $textContent = $(this.selector)

    if (!$textContent || !$textContent.length)
      return

    const $paragraphs = $textContent.find('p')

    if (!$paragraphs || !$paragraphs.length)
      return

    $paragraphs.each((_index, element) => {
      const $p = $(element)
      const originalHtml = $p.html()
      const emails = ToolKit.string.extractEmails(originalHtml)

      if (emails.length > 0) {
        let modifiedHtml = originalHtml
        emails.forEach((email) => {
          // 使用更醒目的高亮样式
          const highlightedEmail = `<span class="${BodyClasses.EMAIL_HIGHLIGHT}">${email}</span>`
          modifiedHtml = modifiedHtml.replace(email, highlightedEmail)
        })

        $p.html(modifiedHtml)
      }
    })
  }

  getMainStyles(): string {
    return `
.text-content {
  ul {
    li {
      color: var(--${PROJECT_PREFIX}-theme-danger-text) !important;
      font-weight: bold !important;
      padding: 2px 6px !important;
    }
  }
}
`
  }
}
